package com.his.his_system.common.filter;

import com.his.his_system.domain.DzmHisAuthGroup;
import com.his.his_system.domain.DzmHisAuthPermissions;
import com.his.his_system.mapper.DzmHisAuthGroupMapper;
import com.his.his_system.mapper.DzmHisAuthPermissionsMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 这个实现类主要是读取数据库中菜单的权限，动态加载权限
 */
@Component
public class MenuFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private DzmHisAuthPermissionsMapper permissionsMapper;
    @Autowired
    private DzmHisAuthGroupMapper authGroupMapper;


    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        Set<ConfigAttribute> set = new HashSet<>();
        // 获取请求地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();

        String fmtUrl  = requestUrl.substring(0,requestUrl.lastIndexOf("/"));
        List<DzmHisAuthPermissions> allMenus = permissionsMapper.selectList(null);
        if (!CollectionUtils.isEmpty(allMenus)) {
            List<String> urlList = allMenus.stream().filter(f -> f.getUrl().endsWith("**") ?
                    fmtUrl.startsWith(f.getUrl().substring(0, f.getUrl().lastIndexOf("/")))
                    : fmtUrl.equals(f.getUrl())).map(menu -> menu.getUrl()).collect(Collectors.toList());
            for (String url : urlList) {
//                QueryWrapper<Role> qr = new QueryWrapper<Role>().eq("url", url);
                List<DzmHisAuthGroup> roles = authGroupMapper.selectAllowUrl(url); //当前请求需要的权限
                if (!CollectionUtils.isEmpty(roles)) {
                    roles.forEach(role -> {
                        SecurityConfig securityConfig = new SecurityConfig(role.getAuthority());
                        set.add(securityConfig);
                    });
                }
            }
        }
//        当前请求不需要权限
        if (ObjectUtils.isEmpty(set)) {
            return null;
        }
        return set;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
